<template>
  <div class="box">
    <div class="basicInfos">
      <el-page-header :icon="ArrowLeft" style="margin-bottom: 20px" @back="comeback">
        <template #content>
          <span class="text-large font-600 mr-3">基本信息</span>
        </template>
      </el-page-header>
      <div class="content">
        <el-form :inline="true" :model="formInline" class="demo-form-inline" :rules="rules">
          <el-form-item label="订单编号">
            <el-input v-model="formInline.orderCode" placeholder="系统自动生成" clearable disabled="true" />
          </el-form-item>
          <el-form-item label="供应商名称" prop="supplierName">
            <el-select v-model="formInline.supplierName" placeholder="请选择供应商名称" clearable>
              <el-option label="厦门巨无霸供应商" value="厦门巨无霸供应商" />
              <el-option label="北京巨有霸供应商" value="北京巨有霸供应商" />
            </el-select>
          </el-form-item>
          <el-form-item label="供应商编码" prop="supplierCode">
            <el-input v-model="formInline.supplierCode" placeholder="请提供供应商编号" clearable />
          </el-form-item>
          <el-form-item label="订单状态">
            <el-select v-model="formInline.state" placeholder="请选择状态" clearable>
              <el-option label="全部确认" value="1" />
              <el-option label="部分确认" value="2" />
              <el-option label="已拒绝" value="3" />
              <el-option label="待确认" value="4" />
              <el-option label="草稿" value="5" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <template #label>
              <el-tooltip
                class="box-item"
                effect="dark"
                content="订单金额（不含税）= SUM{要求的单价（不含税）*要求的数量}"
                placement="bottom"
              >
                <el-icon class="iconView">
                  <QuestionFilled />
                </el-icon>
              </el-tooltip>
              <span>订单金额(不含税)11321</span>
            </template>
            <el-input v-model="formInline.totalPriceWithTax" placeholder="" clearable />
          </el-form-item>
          <el-form-item>
            <template #label>
              <el-tooltip
                class="box-item"
                effect="dark"
                content="订单金额（含税）= SUM{要求的单价（含税）*要求的数量}"
                placement="bottom"
              >
                <el-icon class="iconView">
                  <QuestionFilled />
                </el-icon>
              </el-tooltip>
              <span>订单金额(含税)</span>
            </template>
            <el-input v-model="formInline.totalPriceWithoutTax" placeholder="" clearable />
          </el-form-item>
          <el-form-item label="币种" prop="orderCurrency">
            <el-select v-model="formInline.orderCurrency" placeholder="人民币" clearable>
              <el-option label="人民币" value="人民币" />
              <el-option label="美元" value="美元" />
            </el-select>
          </el-form-item>
          <el-form-item label="采购组织">
            <el-select v-model="formInline.purchaseOrgDesc" placeholder="请选择采购组织" clearable>
              <el-option label="亚太采购组织" value="亚太采购组织" />
              <el-option label="亚购组织" value="亚购组织" />
            </el-select>
          </el-form-item>
          <el-form-item label="采购组">
            <el-select v-model="formInline.purchaseGroupDesc" placeholder="请选择采购组" clearable>
              <el-option label="软件采购组" value="软件采购组" />
              <el-option label="生活采购组" value="生活采购组" />
            </el-select>
          </el-form-item>
          <el-form-item label="订单类型" prop="orderTypeDesc">
            <el-select v-model="formInline.orderTypeDesc" placeholder="请选择订单类型" clearable>
              <el-option label="标准采购订单" value="标准采购订单" />
              <el-option label="标准采购订单" value="标准采购订单" />
            </el-select>
          </el-form-item>
          <el-form-item label="采购企业编码">
            <el-input v-model="formInline.companyCode" placeholder="10031" clearable />
          </el-form-item>
          <el-form-item label="采购企业名称">
            <el-input v-model="formInline.companyName" placeholder="厦门重工有限公司" clearable />
          </el-form-item>
          <el-form-item label="需要确认">
            <el-select v-model="formInline.needConfirm" placeholder="请选择ASN" clearable>
              <el-option label="是" value="1" />
              <el-option label="否" value="0" />
            </el-select>
          </el-form-item>
          <el-form-item label="需要提供ASN">
            <el-select v-model="formInline.publishAsn" placeholder="请选择ASN" clearable>
              <el-option label="不发布" value="0" />
              <el-option label="发布" value="1" />
            </el-select>
          </el-form-item>
          <el-form-item label="订单创建日期">
            <el-input v-model="formInline.createTime" placeholder="创建后系统自动带出" clearable disabled="true" />
          </el-form-item>
          <el-form-item label="订单标识">
            <el-input v-model="formInline.orderDescription" placeholder="采购订单" clearable />
          </el-form-item>
          <el-form-item label="订单备注" class="newline">
            <el-input
              v-model="formInline.orderNotes"
              class="textarea"
              type="textarea"
              placeholder="请输入备注"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>

          <el-upload
            v-model:file-list="fileList"
            class="upload-demo"
            multiple
            :on-preview="handlePreview"
            :before-remove="beforeRemove"
            :limit="3"
            :before-upload="uploadfile"
            :on-exceed="handleExceed"
            :headers="loadfileheaders"
            :http-request="uploading"
            :data="attachmentId"
          >
            <el-button type="primary">
              <el-icon>
                <CirclePlusFilled />
              </el-icon>
              上传附件11
            </el-button>
            <template #tip>
              <div class="el-upload__tip">每个文件最大4M,仅支持pdf,excel,word,jpg,png格式的文件</div>
            </template>
          </el-upload>
        </el-form>
      </div>
    </div>
    <div class="orderDetails">
      <div class="title">订单明细</div>
      <div class="orderContent">
        <div class="orderButton">
          <el-button class="orderAdd" @click="addwuliao">添加物料信息</el-button>
          <el-button class="orderDelete" @click="delwuliaoall">批量删除</el-button>
        </div>
        <div class="orderFrom">
          <el-table
            :data="orderData"
            border
            style="width: 100%"
            :header-cell-style="{
              background: '#f8f8f9',
              color: '#555d70',
              fontWeight: 700,
              fontSize: 15 + 'px',
              padding: 8 + 'px'
            }"
            @row-click="wuliaofocus"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="material_name" label="物料名称" width="150" />
            <el-table-column label="物料编码" prop="material_code" width="150">
              <template #header>
                <span class="star">*</span>
                <span>物料编码11</span>
              </template>
              <template #default="scope">
                <el-select
                  v-model="scope.row.material_code"
                  filterable
                  remote
                  reserve-keyword
                  placeholder="请输入物料编码"
                  :suffix-icon="Search"
                  remote-show-suffix
                  :remote-method="remoteMethod"
                  :loading="loading"
                  @focus="wuliaofocus(scope.row.index, $event)"
                >
                  <el-option v-for="item in options" :key="item.name" :label="item.name" :value="item.name" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="material_spec" label="物料规格" width="150" />
            <el-table-column prop="unit" label="基本计量单位" width="150" />
            <el-table-column prop="batch_id" label="图纸" width="150" />
            <el-table-column prop="packaging_id" label="包装规格" width="150" />
            <el-table-column prop="contract_code" label="合同编号" width="150">
              <template #default="scope">
                <el-select
                  v-model="scope.row.contract_code"
                  filterable
                  remote
                  reserve-keyword
                  placeholder="请输入合同编号"
                  :suffix-icon="Search"
                  remote-show-suffix
                  :remote-method="remoteMethod"
                  :loading="loading"
                >
                  <el-option v-for="item in options" :key="item.name" :label="item.name" :value="item.name" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="number" label="要求数量" width="180">
              <template #header>
                <span class="star">*</span>
                <span>要求数量</span>
              </template>
              <template #default="scope">
                <el-input-number v-model="scope.row.number" controls-position="right" placeholder="请输入数量" />
              </template>
            </el-table-column>
            <el-table-column prop="deliver_date" label="要求的交货日期" width="180">
              <template #header>
                <span class="star">*</span>
                <span>要求的交货日期</span>
              </template>
              <template #default="scope">
                <el-date-picker
                  v-model="scope.row.deliver_date"
                  type="date"
                  placeholder="请选择交货日期"
                  style="width: 150px; height: 2rem"
                />
              </template>
            </el-table-column>
            <el-table-column prop="price" label="要求的单价(不含税)" width="180">
              <template #header>
                <span class="star">*</span>
                <span>要求的单价</span>
              </template>
              <template #default="scope">
                <el-input-number
                  v-model="scope.row.price"
                  controls-position="right"
                  placeholder="请输入单价"
                  width="150"
                />
              </template>
            </el-table-column>
            <el-table-column prop="tax_included_or_not" label="是否含税" width="150">
              <template #header>
                <span class="star">*</span>
                <span>是否含税111</span>
              </template>
              <template #default="scope">
                <el-select v-model="scope.row.tax_included_or_not" placeholder="请选择是否含税" clearable>
                  <el-option
                    v-for="(item, index) in orderDatas"
                    :key="index"
                    :label="item.tax_included_or_not == '1' ? '是' : '否'"
                    :value="item.tax_included_or_not"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="tax_rate" label="税率" width="150">
              <template #header>
                <span class="star">*</span>
                <span>税率</span>
              </template>
              <template #default="scope">
                <el-select v-model="scope.row.tax_rate" placeholder="请选择税率" clearable>
                  <el-option
                    v-for="(item, index) in orderDatas"
                    :key="index"
                    :label="item.tax_rate"
                    :value="item.tax_rate"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="requested_price_with_tax" label="要求的单价(含税)" width="150" />
            <el-table-column prop="factory" label="采购方工厂" width="150">
              <template #header>
                <span class="star">*</span>
                <span>采购方工厂</span>
              </template>
              <template #default="scope">
                <el-select v-model="scope.row.factory" placeholder="请选择工厂" clearable>
                  <el-option
                    v-for="(item, index) in orderDatas"
                    :key="index"
                    :label="item.factory"
                    :value="item.factory"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="unloading_point" label="卸货点" width="150">
              <template #header>
                <span class="star">*</span>
                <span>卸货点</span>
              </template>
              <template #default="scope">
                <el-select v-model="scope.row.unloading_point" placeholder="请选择卸货点" clearable>
                  <el-option
                    v-for="(item, index) in orderDatas"
                    :key="index"
                    :label="item.unloading_point"
                    :value="item.unloading_point"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="150">
              <template #default="scope">
                <el-button class="btndelete" type="danger" @click="handleDelete(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <div class="orderRight">
        <el-button type="primary" class="orderInfoAdd" size="large" @click="orderAdd">添加</el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { Action, FormRules, UploadProps, UploadRawFile, UploadUserFile } from 'element-plus'
import { ArrowLeft, Files, Search } from '@element-plus/icons-vue'
import { useRoute, useRouter } from 'vue-router'
import { orderDetail, orderInfoAdd, orderimports } from '@/api/order'
const router = useRouter()

interface RuleForm {
  supplier_name: string
  supplier_code: string
  order_currency: string
  order_type: string
}
const rules = reactive<FormRules<RuleForm>>({
  supplier_name: [{ required: true, message: '请选择供应商名称', trigger: 'blur' }],
  supplier_code: [{ required: true, message: '请选择供应商编号', trigger: 'blur' }],
  order_currency: [{ required: true, message: '请选择币种', trigger: 'change' }],
  order_type: [{ required: true, message: '请选择订单类型', trigger: 'change' }]
})

//订单明细
const orderDatas = reactive([
  {
    unloading_point: '厦门',
    factory: '厦门',
    tax_rate: '10%',
    tax_included_or_not: '1'
  },
  {
    unloading_point: '杭州',
    factory: '杭州',
    tax_rate: '20%',
    tax_included_or_not: '2'
  }
])

const orderlistnum = ref<number>(1)
interface order {
  index: number
  id: string
  //物流名称
  material_name: string
  //物料编码
  material_code: string
  //物料规格
  material_spec: string
  //基本计量单位
  unit: string
  //图纸
  batch_id: string
  //包装规格
  packaging_id: string
  //合同编号
  contract_code: string
  //要求的数量
  number: string
  //要求的交货日期
  deliver_date: string
  //要求的单价(不含税)
  price: string
  //是否含税
  tax_included_or_not: string
  //税率
  tax_rate: string
  //要求的单价(含税)
  requested_price_with_tax: string
  //采购方工厂
  factory: string
  //卸货点
  unloading_point: string
}

const orderData = ref<order[]>([])

//基本信息
const formInline = ref({
  //订单号
  orderCode: '',
  //供应商名称
  supplierName: '',
  //供应商编码
  supplierCode: '',
  //订单金额(不含税)
  totalPriceWithTax: '',
  //订单总价（含税）
  totalPriceWithoutTax: '',
  //币别
  orderCurrency: '',
  //采购组织编码
  purchaseOrgDesc: '',
  //采购组编码
  purchaseGroupDesc: '',
  //订单类型
  orderTypeDesc: '',
  //公司编码
  companyCode: '',
  //公司名称
  companyName: '',
  //需要确认
  needConfirm: '',
  //提供ASN
  publishAsn: '',
  //创建时间
  createTime: '',
  //订单状态
  state: '',
  //订单标识
  orderDescription: '',
  //订单备注
  orderNotes: ''
})
//添加订单
const orderAdd = () => {
  orderInfoAdd(formInline.value).then((data) => {
    console.log(data)
  })
}

const addwuliao = () => {
  orderData.value.push({
    index: orderlistnum.value,
    id: '',
    material_name: '',
    material_code: '',
    material_spec: '',
    unit: '',
    batch_id: '',
    packaging_id: '',
    contract_code: '',
    number: '',
    deliver_date: '',
    price: '',
    tax_included_or_not: '',
    tax_rate: '',
    requested_price_with_tax: '',
    factory: '',
    unloading_point: ''
  })
  orderlistnum.value++
}
const delwuliaoall = () => {
  ElMessageBox.confirm('你是否要批量删除掉这些数据?', '删除', {
    distinguishCancelAndClose: true,
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    confirmButtonClass: 'propfirmbtn'
  })
    .then(() => {
      const delindeslist: number[] = []
      multipleSelection.value.forEach((item) => {
        delindeslist.push(item.index)
      })
      orderData.value.forEach((item, index) => {
        if (delindeslist.includes(item.index as number)) {
          orderData.value.splice(index, 1)
        }
      })
      ElMessage({
        type: 'success',
        message: '批量删除成功'
      })
    })
    .catch((action: Action) => {
      ElMessage({
        type: 'info',
        message: action === 'cancel' ? '取消删除' : 'Stay in the current route'
      })
    })
}

const handleDelete = (index: number) => {
  ElMessageBox.confirm('你是否要删除掉这条数据?', '删除', {
    distinguishCancelAndClose: true,
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    confirmButtonClass: 'propfirmbtn'
  })
    .then(() => {
      orderData.value.splice(index, 1)
      ElMessage({
        type: 'success',
        message: '删除成功'
      })
    })
    .catch((action: Action) => {
      ElMessage({
        type: 'info',
        message: action === 'cancel' ? '取消删除' : 'Stay in the current route'
      })
    })
}
const multipleSelection = ref<order[]>([])

const handleSelectionChange = (val: order[]) => {
  multipleSelection.value = val
}

// 下拉搜索框
const loading = ref(false)
interface ListItem {
  name: string
  material_spec: string
  unit: string
  batch_id: string
  packaging_id: string
}
const options = ref<ListItem[]>([])
const list = ref<ListItem[]>([
  {
    name: '11111',
    material_spec: '11111111',
    unit: '111111',
    batch_id: '1111111',
    packaging_id: '1111111'
  },
  {
    name: '22222',
    material_spec: '22222',
    unit: '2222',
    batch_id: '222222',
    packaging_id: '22222'
  }
])
const lists = ref<number>(0)
const wuliaofocus = (index: number, e: Event) => {
  lists.value = index - 1
}
const remoteMethod = async (query: string) => {
  if (query) {
    loading.value = true
    //1844663980208033792
    orderDetail(query)
      .then((data) => {
        console.log(data)
      })
      .catch((error) => {
        console.log('错误内容:', error)
      })
    orderData.value[lists.value].material_name = list.value[lists.value].name
    orderData.value[lists.value].material_spec = list.value[lists.value].material_spec
    orderData.value[lists.value].unit = list.value[lists.value].unit
    orderData.value[lists.value].batch_id = list.value[lists.value].batch_id
    orderData.value[lists.value].packaging_id = list.value[lists.value].packaging_id
    setTimeout(() => {
      loading.value = false
      options.value = list.value
    }, 200)
  } else {
    options.value = []
  }
}

const attachmentId = ref({ attachmentId: '666666' })
const uploading = (data) => {
  console.log(data, 23232)
  const formData = new FormData()
  formData.append('files', data.file)
  formData.append('attachmentId', data.data.attachmentId)
  orderimports(formData).then((data) => {
    console.log(data)
  })
}
const loadfileheaders = {
  'Content-Type': 'multipart/form-data'
}

const uploadfile = (rawFile: UploadRawFile) => {
  console.log(rawFile, 1111)
}

//文件上传 orderimports
const fileList = ref<UploadUserFile[]>([])
//点击文件列表中已上传的文件时的钩子
const handlePreview: UploadProps['onPreview'] = (uploadFile) => {
  console.log(uploadFile)
}

//当超出限制时，执行的钩子函数
const handleExceed: UploadProps['onExceed'] = (files, uploadFiles) => {
  ElMessage.warning(
    `The limit is 3, you selected ${files.length} files this time, add up to ${
      files.length + uploadFiles.length
    } totally`
  )
}
//删除文件之前的钩子，参数为上传的文件和文件列表
const beforeRemove: UploadProps['beforeRemove'] = (uploadFile, uploadFiles) => {
  return ElMessageBox.confirm(`Cancel the transfer of ${uploadFile.name} ?`).then(
    () => true,
    () => false
  )
}

const comeback = () => {
  router.push({
    name: 'orderPage',
    query: {}
  })
}
</script>

<style lang="scss" scoped>
.box {
  background: #f8f8f8;
  width: 100%;
  box-sizing: border-box;
  padding: 15px 0;

  .basicInfos {
    width: 98%;
    margin: 0px auto;
    padding: 20px 30px;
    box-sizing: border-box;
    background: #fff;

    .title {
      font-size: 18px;
      font-weight: 800;
    }

    .content {
      margin-top: 20px;

      .iconView {
        color: #89be6b;
      }

      .newline {
        display: flex;
        align-items: normal;
        width: 97%;

        .textarea {
          font-size: 15px;
        }
      }

      .upload-demo {
        margin-left: 9rem;

        i {
          color: #578c43;
          font-size: 16px;
        }

        .el-upload__tip {
          color: #bfbfbf;
        }
      }
    }
  }

  .orderDetails {
    margin: 0px auto;
    margin-top: 25px;
    width: 98%;
    padding: 20px 30px;
    box-sizing: border-box;
    background: #fff;

    .title {
      font-size: 18px;
      font-weight: 800;
    }

    .orderContent {
      .orderButton {
        margin: 30px 0px 20px;

        .orderAdd {
          border-radius: 6px;
          font-size: 15px;
          color: #fff;
          background: #578c43;
          height: 40px;
        }

        .orderDelete {
          border-radius: 6px;
          height: 40px;
          font-size: 15px;
        }
      }
    }

    .orderFrom {
      .btndelete {
        font-size: 15px;
        padding-left: 0 !important;
      }

      .star {
        color: red;
        margin-right: 4px;
        vertical-align: middle;
      }
    }

    .orderRight {
      display: flex;
      flex-direction: row-reverse;

      .orderInfoAdd {
        width: 6rem;
        font-size: 15px;
        border-radius: 6px;
        margin-top: 30px;
        color: #fff;
        background: #578c43;
      }
    }
  }
}

::v-deep .el-form--inline .el-form-item {
  align-items: center;
  margin-right: 47px;
}

::v-deep .el-input--small .el-input__wrapper {
  padding: 7px;
  font-size: 15px;
}

::v-deep .el-select--small .el-select__wrapper {
  padding: 11px 7px;
  font-size: 15px;
}

::v-deep .content .el-form-item__content {
  width: 34rem;
}

::v-deep .content .el-form-item__label {
  width: 9rem;
  font-size: 15px;
}

::v-deep .content .newline .el-textarea__inner {
  height: 100px;
}

::v-deep .upload-demo .el-button--primary {
  width: 135px;
  border: 1px dashed #e2e2e2;
  background: none;
  border-radius: 0;
  color: #000;
  width: 280px;
  height: 45px;
}

.el-table--small .cell {
  padding: 5px 8px;
}

::v-deep .orderFrom .el-button,
.el-button.is-round {
  background: none;
  color: #699666;
  border: none;
  padding: 0;
}

::v-deep .el-table--enable-row-transition .el-table__body td.el-table__cell {
  font-size: 15px;
  padding: 13px 10px;
}

::v-deep .el-input-number.is-controls-right[class*='small'] [class*='decrease'] {
  --el-input-number-controls-height: 50%;
}

::v-deep .el-input-number.is-controls-right[class*='small'] [class*='increase'] {
  --el-input-number-controls-height: 50%;
}
</style>
